package crawler

import (
	"encoding/json"
	"github.com/PuerkitoBio/goquery"
	"github.com/axgle/mahonia"
	"log"
	"net/http"
	"strings"
)

var decode1688 = mahonia.NewDecoder("gbk")

func Crawl1688(url string) string {
	res, err := http.Get(url)
	if err != nil {
		log.Println(err)
		return ""
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		log.Println("status code error: %d %s", res.StatusCode, res.Status)
		return ""
	}
	utfBody := decode1688.NewReader(res.Body)
	doc, err := goquery.NewDocumentFromReader(utfBody)
	if err != nil {
		log.Println(err)
		return ""
	}
	companyName := doc.Find(".contact-info").Find("h4").Text()
	contactPerson := doc.Find(".contact-info").Find("dl").First().Find("dd").Find("a").First().Text()
	contctDescDoc := doc.Find(".fd-line").Find(".contcat-desc")
	telPhone := contctDescDoc.Find("dl").Find("dd").Eq(0).Text()
	mobile := contctDescDoc.Find(".m-mobilephone").Find("dd").Text()
	address := contctDescDoc.Find(".address").Text()
	contactInfo := ContactInfo1688{companyName, contactPerson, telPhone, strings.TrimSpace(mobile), address}
	return contactInfo.ToJson()
}

func (t *ContactInfo1688) ToJson() string {
	bytes, _ := json.Marshal(t)
	return string(bytes)
}

type ContactInfo1688 struct {
	CompanyName   string
	ContactPerson string
	TelPhone      string
	Mobile        string
	Address       string
}

type IToJson interface {
	ToJson() string
}
